import Mock from 'mockjs'
import store from '../store'


// 拦截活跃用户请求并返回相关数据
Mock.mock('/users/active', 'get', () => {
    // 使用派生状态
    let articles = store.getters.computedArticles

    let comments = []
    let usersObj = {}

    let activeUers = []

    // 获取评论
    articles.map((article) => {
        const articleComments = Array.isArray(article.comments) ? article.comments : []
        // 合并评论
        comments = [...comments, ...articleComments]
    })

    // 统计用户发布评论的数量，并返回包含头像和数量的对象
    // 多值转单值
    usersObj = comments.reduce((accumulator, currentValue) => {
        accumulator[currentValue.uname] = accumulator[currentValue.uname] || {}
        accumulator[currentValue.uname].avatar = currentValue.uavatar
        accumulator[currentValue.uname].num += accumulator[currentValue.uname].num || 1
        return accumulator
    }, {})

    // 将统计后的数据放入一个数组，获取对象视图
    for (const [key, vaule] of Object.entries(usersObj)) {
        activeUers.push({
            name: key,
            avatar: vaule.avatar,
            num: vaule.num
        })
    }

    // 将发布最多的用户排在前面
    activeUers.sort((a, b) => b.num - a.num)
    activeUers = activeUers.slice(0, 8)

    return activeUers
})

// 拦截最热文章请求并返回相关数据，请求方法为 POST
Mock.mock('/articles/hot', 'post', (options) => {
    let filteredArticles = store.getters.getArticlesByFilter('noreply')
    let articles = filteredArticles.reverse()

    // 取7天内评论最多的文章
    let hotArticles = articles.filter((article) => (new Date() - new Date(article.date) < 604800000))
    let num

    // 查询条件为json字符串形式
    if (options.body) {
        try {
            num = JSON.parse(options.body).num
        } catch (e) {
            return null
        }
    }

    hotArticles = hotArticles.slice(0, num || 7)
    return hotArticles
})